import React, { useState, useEffect } from 'react';
import {Modal, Form, Input, Select, Button, message} from 'antd';
import {getAcademyInfo} from "../../../api/academy.js";

const { Option } = Select;

const SpecialtyModal = ({ visible, onCancel, onOk, editingRecord }) => {
    const [form] = Form.useForm();
    const [academyList, setAcademyList] = useState([]);
    const [loading, setLoading] = useState(false);
    const fetchAcademyInfo = async () => {
        setLoading(true);
        try {
            const res = await getAcademyInfo(null);
            setAcademyList(res.data);
        } catch (error) {
            message.error('获取学院列表失败');
            console.error(error);
        } finally {
            setLoading(false);
        }
    };

    useEffect(() => {
        if (visible) {
            fetchAcademyInfo();
            if (editingRecord) {
                form.setFieldsValue(editingRecord);
            } else {
                form.resetFields();
            }
        }
    }, [visible, editingRecord]);

    const handleOk = () => {
        form.validateFields().then(values => {
            onOk(values);
            form.resetFields();
        });
    };

    return (
        <Modal
            title={editingRecord ? '编辑专业信息' : '新增专业信息'}
            open={visible}
            onOk={handleOk}
            onCancel={() => {
                form.resetFields();
                onCancel();
            }}
            footer={[
                <Button key="cancel" onClick={() => {
                    form.resetFields();
                    onCancel();
                }}>
                    取消
                </Button>,
                <Button key="submit" type="primary" onClick={handleOk}>
                    提交
                </Button>
            ]}
        >
            <Form form={form} layout="vertical" name="specialty_form">
                <Form.Item label="所属学院" name="academyId" rules={[{ required: true, message: '请选择学院！' }]}>
                    <Select
                        showSearch
                        loading={loading}
                        placeholder="请选择学院"
                        optionFilterProp="children"
                        filterOption={(input, option) =>
                            option.children.toLowerCase().includes(input.toLowerCase())
                        }
                    >
                        {academyList.map(academy => (
                            <Option key={academy.id} value={academy.id}>
                                {academy.academyName}
                            </Option>
                        ))}
                    </Select>
                </Form.Item>

                <Form.Item
                    label="专业名称"
                    name="specialtyName"
                    rules={[{ required: true, message: '请输入专业名称！' }]}
                >
                    <Input placeholder="请输入专业名称" />
                </Form.Item>

                <Form.Item
                    label="专业代码"
                    name="specialtyCode"
                    rules={[
                        { required: true, message: '请输入专业代码！' },
                        {
                            pattern: /^\d{2}$/,
                            message: '请输入两位数字的专业代码（如 01、10）'
                        }
                    ]}
                >
                    <Input
                        placeholder="请输入两位数字专业代码（如 01、10）"
                        maxLength={2}
                        onChange={(e) => {
                            // 只允许输入数字
                            const value = e.target.value.replace(/[^0-9]/g, '');
                            e.target.value = value;
                        }}
                    />
                </Form.Item>
            </Form>
        </Modal>
    );
};

export default SpecialtyModal;